package cn.lk1234.imt.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.lk1234.imt.bean.UserInfo;
import cn.lk1234.imt.dao.dbtool.MapBean;
import cn.lk1234.imt.service.UserService;
import cn.lk1234.imt.utils.SessionAttributeUtils;

@Controller
public class LoginController {
	@Autowired
	public UserService userService;

	/**
	 * 读取登录页
	 */
	@RequestMapping(value = "/toLoginPage")
	public ModelAndView toLoginPage() throws IOException {
		ModelAndView view = null;
		view = new ModelAndView("login");
		//throw new IOException();
		return view;
	}

	/**
	 * 点击登录按钮
	 */
	@RequestMapping(value = "/login")
	public @ResponseBody String login(HttpServletRequest request,
			HttpServletResponse response,UserInfo user) throws IOException, SQLException {
		
		HttpSession session = request.getSession();
		String result = "OK";
		// 返回值也可以做成json方便回显失败信息
		try {
			// 调用Service层
			List<MapBean> userList = userService.login(user);
			// 判断返回结果是否存在
			if (userList != null && userList.size() > 0) {
				result = "OK";
				session.invalidate();
				SessionAttributeUtils.setSessionAttribute(request, "userName",userList.get(0).getData().get("USER_NAME"));
			} else {
				result = "ERROR";
			}
		} catch (Exception e) {
			result = "ERROR:" + e.getMessage();
		}
		return result;
	}
	
	/**
	 * 退出登录
	 */
	@RequestMapping(value = "/loginOut")
	public ModelAndView loginOut(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		ModelAndView view = null;
		HttpSession session = request.getSession();
		//销毁session
		session.invalidate();
		view = new ModelAndView("redirect:/", null);
		//throw new IOException();
		return view;
	}

}
